package me.weijing.common.http;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.GeneralSecurityException;
import java.security.cert.X509Certificate;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.X509TrustManager;

import android.os.AsyncTask;
import android.util.Log;

public class HttpUtil {
    /**
     * 同步请求图片、音频等文件
     * 
     * @param url
     * @return
     */
    static {
        myX509TrustManager xtm = new myX509TrustManager();
        myHostnameVerifier hnv = new myHostnameVerifier();
        SSLContext sslContext = null;
        try {
            sslContext = SSLContext.getInstance("TLS"); // 或SSL
            X509TrustManager[] xtmArray = new X509TrustManager[] { xtm };
            sslContext.init(null, xtmArray, new java.security.SecureRandom());
        } catch (GeneralSecurityException e) {
            e.printStackTrace();
        }
        if (sslContext != null) {
            HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());
        }
        HttpsURLConnection.setDefaultHostnameVerifier(hnv);

    }

    public static byte[] syncRequestResource(String url) {
        Log.i("TAG", url);
        InputStream in = null;
        ByteArrayOutputStream bos = null;
        HttpURLConnection conn = null;

        try {
            URL getUrl = new URL(url);
            conn = (HttpURLConnection) getUrl.openConnection();
            conn.setConnectTimeout(5000);
            conn.setRequestMethod("GET");
            conn.connect();
            // int fileSize=conn.getContentLength();
            // long lastModify=conn.getLastModified();
            in = conn.getInputStream();
            bos = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = in.read(buffer)) != -1) {
                bos.write(buffer, 0, len);
            }
            return bos.toByteArray();
        } catch (Exception e) {
            e.printStackTrace();
        } catch (Throwable e) {
            e.printStackTrace();
        } finally {
            if (conn != null) {
                conn.disconnect();
                conn = null;
            }
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    /**
     * 同步请求图片、音频等文件
     * 
     * @param url
     * @return CachedFile
     */
    public static String syncRequestResource2File(String url) {
        return syncRequestResource2File(url, null);
    }

    public static String syncRequestResource2File(String url, AsyncTask<String, Integer, Object> callTask) {
        InputStream in = null;
        // ByteArrayOutputStream bos = null;
        HttpURLConnection conn = null;
        String outFile = FileCacheStore.genNewCacheFile();
        FileOutputStream fos = null;
        File of = new File(outFile);
        try {
            URL getUrl = new URL(url);

            conn = (HttpURLConnection) getUrl.openConnection();
            conn.setConnectTimeout(8000);
            conn.setRequestMethod("GET");
            conn.connect();
            in = conn.getInputStream();
            fos = new FileOutputStream(of);
            byte[] buffer = new byte[1024];
            int len = 0;
            int icount = 0;
            while ((len = in.read(buffer)) != -1) {
                if (null != callTask && callTask.isCancelled()) {
                    of.delete();
                    return null;
                }
                fos.write(buffer, 0, len);
                icount++;
                if (icount >= 16) {
                    fos.flush();
                    icount = 0;
                }
            }
            return outFile;
        } catch (Exception e) {
            e.printStackTrace();
        } catch (Throwable e) {
            e.printStackTrace();
        } finally {
            if (conn != null) {
                conn.disconnect();
                conn = null;
            }
            if (in != null) {
                try {
                    in.close();
                } catch (Throwable e) {
                    e.printStackTrace();
                }
            }
            if (fos != null) {
                try {
                    fos.close();
                } catch (Throwable e) {
                    e.printStackTrace();
                }
            }
        }
        of.delete();
        return null;
    }

    public static class myX509TrustManager implements X509TrustManager {

        @Override
        public void checkClientTrusted(X509Certificate[] chain, String authType) {
        }

        @Override
        public void checkServerTrusted(X509Certificate[] chain, String authType) {
        }

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }
    }

    public static class myHostnameVerifier implements HostnameVerifier {

        @Override
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }
    }
}
